package com.edunera.connection;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import com.edunera.R;


public abstract class BaseTask extends AsyncTask<Void,Void,Void> {
    private final Context context;
    protected ProgressDialog progress;
    protected Exception exception;

    public BaseTask(Context context, int messageId) {
        super();
        this.context = context;
        progress = new ProgressDialog(context);
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setCancelable(false);
        progress.setIndeterminate(true);
        progress.setMessage(context.getString(messageId));
    }

    @Override
    protected void onPreExecute() {
        try {
            if(progress!= null) {
                progress.show();
            }
        } catch (Exception ignored) {

        }
    }

    @Override
    protected Void doInBackground(Void ... params) {

        try{
            if(isConnected()) {
                doTask();
            } else {
                throw new NoConnectionException();
            }

        } catch (Exception e) {

            this.exception = e;

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        try {
            if (progress != null && progress.isShowing())
                progress.dismiss();
        } catch (Exception ignored) {
        }

        if (exception != null) {
            onException();
        } else {

            onComplete();

        }
    }


    public abstract void doTask();
    public abstract void onComplete();
    public void onException(){

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setCancelable(false)
                .setNeutralButton(R.string.ok, null);

        try{
            throw exception;
        } catch (NoConnectionException e) {
            builder.setMessage(R.string.no_connection);
        } catch (Exception e) {
            builder.setMessage(R.string.general_error);

        }
    }

    private  boolean isConnected() {

        ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = conMgr.getActiveNetworkInfo();

        if (info != null && info.isConnected()) {
            Log.v("NetworkInfo", "Connected State");
        } else {

            Log.v("conMgr", " No Connection");

        }


        return (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable() && conMgr
                .getActiveNetworkInfo().isConnected());
    }

    public class NoConnectionException extends Exception {
    }

}
